package com.chuangjiangx.member.basic.web.controller;

import com.chuangjiangx.commons.CurrentThreadContext;
import com.chuangjiangx.commons.exception.BaseException;
import com.chuangjiangx.commons.response.Response;
import com.chuangjiangx.commons.response.ResponseUtils;
import com.chuangjiangx.commons.response.UnderlineResponse;
import com.chuangjiangx.commons.wx.auth.WXWebAuthType;
import com.chuangjiangx.member.coupon.ddd.application.ActivateWxCardApplication;
import com.chuangjiangx.member.basic.ddd.application.EntryApplication;
import com.chuangjiangx.member.coupon.ddd.application.MbrCardApplication;
import com.chuangjiangx.member.coupon.ddd.application.MbrCouponApplication;
import com.chuangjiangx.member.coupon.ddd.application.command.ActivateWxCardCommand;
import com.chuangjiangx.member.coupon.ddd.application.result.MbrActivateWxCardResult;
import com.chuangjiangx.member.coupon.ddd.domain.model.MbrWxCard;
import com.chuangjiangx.member.coupon.ddd.domain.repository.MbrWxCardRepository;
import com.chuangjiangx.member.common.PageUrlConstant;
import com.chuangjiangx.member.basic.web.interceptor.Login;
import com.chuangjiangx.member.basic.web.request.CanGiftCardRequest;
import com.chuangjiangx.member.basic.web.request.SearchCardDetailRequest;
import com.chuangjiangx.member.coupon.web.response.response.CanGiftCardResponse;
import com.chuangjiangx.member.basic.web.response.SearchCardDetailResponse;
import com.chuangjiangx.member.coupon.ddd.query.MbrCardQuery;
import com.chuangjiangx.member.basic.ddd.query.MemberQuery;
import com.chuangjiangx.member.basic.ddd.query.MerchantUserInfoQuery;
import com.chuangjiangx.member.basic.ddd.query.condition.CanSyncWxCondition;
import com.chuangjiangx.member.basic.ddd.query.dto.MbrConfigDTO;
import com.chuangjiangx.member.basic.ddd.query.dto.MemberDTO;
import com.chuangjiangx.member.basic.ddd.domain.model.MbrUserContext;
import com.chuangjiangx.member.basic.ddd.domain.model.MbrUserMappingType;
import com.chuangjiangx.member.basic.ddd.domain.model.MemberId;
import com.chuangjiangx.member.basic.ddd.domain.model.MerchantId;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpSession;

/**
 * @Auther: YZJ
 * @Date: 2018/8/29 00:56
 * @Description:微信会员卡接口
 */
@Slf4j
@RestController
@RequestMapping(value = "/h5/mbr-wx-card")
@Api(value = "MbrWxCardController", tags = "微信会员卡", description = "")
public class MbrWxCardController extends BaseController {
    @Autowired
    private ActivateWxCardApplication activateWxCardApplication;
    @Autowired
    private MemberQuery memberQuery;
    @Autowired
    private MbrCardApplication mbrCardApplication;
    @Autowired
    private MbrCardQuery mbrCardQuery;
    @Autowired
    private MbrWxCardRepository mbrWxCardRepository;
    @Autowired
    private MbrCouponApplication mbrCouponApplication;
    @Autowired
    private MerchantUserInfoQuery merchantUserInfoQuery;
    @Autowired
    private EntryApplication entryApplication;


    /**
     * 判断能否同步微信卡包
     *
     * @throws Exception
     */
    @PostMapping(value = "/can-sync-wx")
    @ApiOperation(value = "判断能否同步微信卡包")
    @Login
    public Response canSyncWx()throws Exception{
        MbrUserContext user = (MbrUserContext) CurrentThreadContext.getCurrentUser();
        Assert.notNull(user,"用户信息不存在");
        CanSyncWxCondition canSyncWxCondition = new CanSyncWxCondition();
        canSyncWxCondition.setMemberId(new MemberId(user.getMemberId()));
        canSyncWxCondition.setMerchantId(new MerchantId(user.getMerchantId()));
        int status = memberQuery.canSyncWx(canSyncWxCondition);
        return ResponseUtils.successCamel(status);
    }


    @ApiOperation(value = "判断能否支付后领卡")
    @PostMapping(value = "can-gift-card")
    public UnderlineResponse<CanGiftCardResponse> canGiftCard(@RequestBody @Validated CanGiftCardRequest request){
        String cardName = mbrCardApplication.canGiftCard(request.getOrderNumber(),request.getMerchantId(),request.getOpenId());
        CanGiftCardResponse response = new CanGiftCardResponse();
        response.setCardName(cardName);
        return (UnderlineResponse)ResponseUtils.success(response);
    }

    @ApiOperation(value = "获取会员卡详情")
    @PostMapping(value = "search-card-detail")
    public UnderlineResponse<SearchCardDetailResponse> searchCardDetail(@RequestBody @Validated SearchCardDetailRequest request){
        MbrConfigDTO mbrConfigDTO = mbrCardQuery.searchCardDetail(request.getMerchantId());
        SearchCardDetailResponse response = new SearchCardDetailResponse();
        BeanUtils.copyProperties(mbrConfigDTO,response);
        return (UnderlineResponse)ResponseUtils.success(response);
    }
    /**
     * 微信会员卡激活
     *
     */
    @GetMapping(value = "/activation-wx-card")
    @ApiOperation(value = "激活微信会员卡")
    public ModelAndView activationWxCard(@RequestParam String card_id,@RequestParam String encrypt_code,@RequestParam String openid) {
        ActivateWxCardCommand cardCommand = new ActivateWxCardCommand();
        cardCommand.setCardId(card_id);
        cardCommand.setEncryptCode(encrypt_code);
        cardCommand.setOpenid(openid);
        MbrActivateWxCardResult result = activateWxCardApplication.activateWxCard(cardCommand);
        return new ModelAndView("forward:/h5/mbr-wx-card/redirect/active-wx-card");
//        return new ModelAndView("redirect:"+ PageUrlConstant.HOME_PAGE+result.getMerchantId()+"&cardId="+card_id+"&code="+result.getCode());
    }

    @ApiOperation(value = "微信会员卡重定向")
    @RequestMapping(value = "/redirect/{uri}",method = RequestMethod.GET)
    public ModelAndView wxMerchantCallback(
            HttpSession session,
            @PathVariable String uri,
            @RequestParam String card_id,
            @RequestParam String encrypt_code,
            @RequestParam String openid){
        MbrWxCard mbrWxCard = mbrWxCardRepository.fromWxCardId(card_id);
        if(mbrWxCard == null){
            throw new BaseException("","未查到微信会员卡信息");
        }
        MerchantId merchantId = mbrWxCard.getMerchantId();
        //解码
        String cardNo = mbrCouponApplication.codeDecrypt(encrypt_code,merchantId);
        // 去除空格
        cardNo = cardNo.replaceAll("\\s","");
        //自动登录
        MbrUserContext userContext = loginService.currentUserContext();
        userContext.setMerchantId(merchantId.getId());
        loginService.saveUserContext(userContext);
        if(!isValidLogin(userContext,merchantId.getId())){
            //未登录,做自动登录
            MemberDTO dto = memberQuery.queryByCardNO(cardNo);
            if(null == dto){
                throw new BaseException("","会员卡号:"+cardNo+"不存在!");
            }
            Long defaultMerchantUserId = merchantUserInfoQuery.getDefaultMerchantUserId(merchantId.getId());
            userContext = MbrUserContext.builder()
                    .memberId(dto.getId())
                    .merchantId(dto.getMerchantId())
                    .headimgurl(dto.getHeadimgurl())
                    .mbrUserMappingType(MbrUserMappingType.WX)
                    .merchantUserId(defaultMerchantUserId)
                    .mobile(dto.getMobile())
                    .name(dto.getName())
                    .sex(dto.getSex())
                    .state(MbrUserContext.State.MEMBER)
                    .openId(dto.getOpenid())
                    .build();
            loginService.saveUserContext(userContext);
            //TODO 需要优化
            if(StringUtils.isBlank(userContext.getOpenId())){
                session.setAttribute("needIsvOpenId",uri);
                session.setAttribute("cardId",card_id);
                session.setAttribute("code",cardNo);
                String isvWxWebAuthUrl = entryApplication.isvWxWebAuthUrl(merchantId.getId(), WXWebAuthType.BASE);
                return new ModelAndView("redirect:" + isvWxWebAuthUrl);
            }
        }
        ModelAndView modelAndView = fromWxCardRedirect(userContext,uri, merchantId.getId(),card_id,cardNo);
        return modelAndView;
    }

    @RequestMapping(value = "/isv-openid/redirect",method = RequestMethod.GET)
    public ModelAndView wxMerchantCallback(
            HttpSession session
    ){
        MbrUserContext userContext = loginService.currentUserContext();
        if(null == userContext.getMerchantId() || null == userContext.getMobile()){
            throw new BaseException("","自动登录错误!");
        }
        String uri = (String) session.getAttribute("needIsvOpenId");
        String cardId = (String) session.getAttribute("cardId");
        String code = (String) session.getAttribute("code");
        //清除标记
        session.removeAttribute("needIsvOpenId");
        session.removeAttribute("cardId");
        session.removeAttribute("code");
        return fromWxCardRedirect(userContext,uri,userContext.getMerchantId(),cardId,code);
    }

    private ModelAndView fromWxCardRedirect(MbrUserContext userContext,String uri, Long merchantId,String cardId,String code) {
        ModelAndView modelAndView = new ModelAndView();
        switch (uri){
            case "rechargeRule":
                modelAndView.setViewName("redirect:"+ PageUrlConstant.page(PageUrlConstant.RECHARGE_RULE,merchantId));
                break;
            case "pointList":
                modelAndView.setViewName("redirect:"+ PageUrlConstant.page(PageUrlConstant.POINT_LIST,merchantId));
                break;
            case "myCouponPackage":
                modelAndView.setViewName("redirect:"+ PageUrlConstant.page(PageUrlConstant.MY_COUPON_PACKAGE,merchantId));
                break;
            case "index":
                modelAndView.setViewName("redirect:"+ PageUrlConstant.page(PageUrlConstant.HOME_PAGE,merchantId));
                break;
            case "nearbyStores":
                modelAndView.setViewName("redirect:"+ PageUrlConstant.page(PageUrlConstant.NEARBY_STORES,merchantId));
                break;
            case "storeList":
                modelAndView.setViewName("redirect:"+ PageUrlConstant.page(PageUrlConstant.STORE_LIST,merchantId));
                break;
            case "active-wx-card":
                modelAndView.setViewName("redirect:"+ PageUrlConstant.page(PageUrlConstant.HOME_PAGE,merchantId)+"&cardId="+cardId+"&code="+code);
                break;
            case "coupon-use-immediately":
                // 微信卡包中的卡券-立即使用
                modelAndView.setView(new RedirectView(PageUrlConstant.page(PageUrlConstant.C_TO_B_PAGE,merchantId)+"&openid="+userContext.getOpenId()+"&verifyCode="+code));
                break;
            default:
                modelAndView.setViewName("redirect:" + PageUrlConstant.page(PageUrlConstant.LOGIN_PAGE,merchantId));
                break;
        }
        return modelAndView;
    }


}
